// An example Backbone application contributed by
// [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple
// [LocalStorage adapter](backbone.localStorage.html)
// to persist Backbone models within your browser.

// Load the application once the DOM is ready, using `jQuery.ready`:
$(function() {
	
	var AppTopView = Backbone.View.extend({
		template : _.template($('#appTopTel').html()),
		initialize : function() {
			this.$el = $(this.template());
			$("#app").append(this.$el);
		}
	});

	var Article = Backbone.Model.extend({
		url: "/article/2.6672257693228613e+28",
		defaults : function() {
			return {
				id : "",
				caption : "",
				content : "",
				count : "",
				createTime : ""
			};
		}

	});

	var ArticleList = Backbone.Collection.extend({
		url : "/article/list/1",
		model : Article,
	});

	var ArticleItemView = Backbone.View.extend({
		template : _.template($('#articleItemTel').html()),
		initialize : function() {
			this.listenTo(this.model, 'change', this.render);
		},
		render : function() {
			this.$el = $(this.template(this.model.toJSON()));
			return this;
		}

	});
	
	var ArticleView = Backbone.View.extend({
		template : _.template($('#articleTel').html()),
		initialize : function() {
			this.listenTo(this.model, 'change', this.render);
			this.model.fetch({
				success : function(model, response) {

				},
				error : function(e) {

				}
			});
		},
		render : function() {
			console.log("ArticleView.render()已执行!");
			this.$el = $(this.template(this.model.toJSON()));
			$("#app").empty().append(this.$el);
			return this;
		}

	});
	
	var AppView = Backbone.View.extend({
		page: 1,
		el: $('<div id="articleList" class="row animated lightSpeedIn"></div>'),
		initialize : function() {
			
			//清除已有的View
			$("#app").empty();
			
			this.appTopView = new AppTopView; //显示顶部
			this.articles = new ArticleList;	//文章列表模型
			$("#app").append(this.$el);			//显示文章列表
			
			this.listenTo(this.articles, 'add', this.addOne);
			this.listenTo(this.articles, 'reset', this.addAll);
			console.log("this.articles",this.articles);
			this.articles.fetch();
		},
		addOne : function(res) {
			var view = new ArticleItemView({
				model : res
			});
			this.$el.append(view.render().$el);
			console.log("执行了addOne事件!");
		},
		addAll : function() {
			this.articles.each(this.addOne, this);
			console.log("执行了重置事件!"); 
		}
	});

	var AppRouter = Backbone.Router.extend({
		routes : {
			'' : 'index',
			"article/:id" : "getArticle",
		},
		getArticle: function(id) {
			articleView = new ArticleView({model : _.extend(new Article(),{ url : '/article/' + id })});
	    },
	    index : function() {
			appView = new AppView;
		}
	});
	
	var router = new AppRouter();
	Backbone.history.start();
});
